"""
@Time : 2023/7/29 11:52
@Author : chenxiaoliang
@File : query_book_his.py
@Description : 查询书籍历史借阅记录
"""
import sys
from flask_restful import Resource, reqparse

from service.mysql_connect import MySQLConnected
from service.config_import import load_yaml

sys.path.append('..')

parser = reqparse.RequestParser()
parser.add_argument('book_id', type=int, help="不能为空", required=True)


class QueryBookHis(Resource):
    def post(self):
        args = parser.parse_args()
        book_id = args.get('book_id')

        yaml_config_path = "config_info.yaml"
        params = load_yaml(yaml_config_path)
        dbinfo = params['databases']['library_db_info']
        db = params['databases']['library_db_name']

        connected = MySQLConnected(dbinfo)

        sql_for_book_status = "select status from " + db + ".books where id = %s"
        connected.cur.execute(sql_for_book_status, str(book_id))
        book_status = connected.cur.fetchall()
        if not book_status:
            return {'content': '不存在对应书籍，请确认', 'result': 'failure'}

        sql = "select borrower_id,(select name from " + db + \
              ".borrowers where id = borrower_id) as borrower_name,borrow_time,return_time from " + db + \
              ".books_borrowers_relation where book_id = %s order by borrow_time desc"
        connected.cur.execute(sql, book_id)
        result_tuple = connected.cur.fetchall()
        resp_data = []
        for record in result_tuple:
            temp_dict = dict()
            temp_dict['borrower_id'] = record[0]
            temp_dict['borrower_name'] = record[1]
            temp_dict['borrower_time'] = record[2]
            temp_dict['return_time'] = record[-1]
            resp_data.append(temp_dict)

        connected.cur.close()
        connected.con.close()
        return {'result': 'success', 'content': resp_data, 'count': len(resp_data)}
